package com.gc.realm;

import com.gc.UserUtil;
import com.gc.entity.Users;
import com.gc.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created by Administrator on 2018/1/28.
 */
public class MyUserRealm extends AuthorizingRealm {

    @Autowired
    UserService us;

    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //授权
        System.out.println("授权");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
       /* String name = principalCollection.getPrimaryPrincipal().toString();

        authorizationInfo.setStringPermissions(UserUtil.getPermissionByName(name));
        authorizationInfo.setRoles(UserUtil.getRoleByName(name));*/
        Users users = (Users) SecurityUtils.getSubject().getSession().getAttribute("user");
        authorizationInfo.setStringPermissions(us.getUserPermission(users.getId()));
        return authorizationInfo;
    }

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //登录验证
        System.out.println("验证");
        String name = authenticationToken.getPrincipal().toString();
        String password = new String((char[])authenticationToken.getCredentials());
        //Users user = UserUtil.CheckName(name);
        Users user = us.login(name,password);
        if(user==null){
            throw new UnknownAccountException("用户名不存在！");
        }
        if(!user.getUserpwd().equals(password)){
            throw new IncorrectCredentialsException("密码输入错误！");
        }
        SecurityUtils.getSubject().getSession().setAttribute("user",user);
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(name,password,this.getName());
        return authenticationInfo;
    }
}
